import axios from './config'
import encrypt from '../encrypt'
import Global from '../global'
import {MessageBox} from 'mint-ui'

var httpRequest = function (resolve, reject, config, isRetry) {
  axios(config)
    .then(response => {
      // 请求接口正确且成功时
      if (response.data.status === 200) {
        resolve(response.data.result ? response.data.result : response)
      } else {
        // 请求接口错误或不成功时
        resolve(response.data.result ? response.data.result : response)
      }
    }).catch(error => {
      MessageBox.alert(`网络异常！status:${error.response.status}`)
      reject(error)
    })
}

/**
 * 简单封装axios
 */
axios.ajax = function ajax (url, method, params, form = false) {
  return new Promise((resolve, reject) => {
    let aes_key = Global.getRandomAesKey()
    let config = null
    if (form) {
      config = {
        url: url,
        method: method,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'aes_key': encrypt.JsEncrypt().encrypt(aes_key)
        }
      }
      config.transformRequest = [
        function (data) {
          let ret = ''
          for (let it in data) {
            ret +=
							encodeURIComponent(it) +
							'=' +
							encodeURIComponent(data[it]) +
							'&'
          }
          return ret
        }
      ]
    } else {
      config = {
        url: url,
        method: method
      }
      config.headers = {
        'Content-type': 'application/json;charset=utf-8',
        'aes_key': encrypt.JsEncrypt().encrypt(aes_key)
      }
    }
    if (method && method.toLowerCase() === 'get') {
      config.params = params
    } else {
      config.data = params
    }
    httpRequest(resolve, reject, config)
  })
}

axios.interceptors.request.use( (config) => {
  if(config.method == 'post' && !Global.getDebug()) {
    // console.log(crypto.EncryptData(JSON.stringify({'a': 'xxxxxxx'})))
    config.data = encrypt.EncryptData(JSON.stringify(config.data))
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

axios.interceptors.response.use((response) => {
  if(!Global.getDebug() && typeof(response.data) == 'string') {
    response.data = encrypt.DecryptData(response.data)
  }
  return response
}, (error) => {
  return Promise.reject(error)
})

export default axios
